package controller;

import entity.Article;
import entity.MyResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import service.ArticleService;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Controller
public class ArticleController {
    @Autowired
    private ArticleService articleService;
    @ResponseBody
    @PostMapping("/uploadImg")
    public MyResult<Map> uploadImg(MultipartFile file) throws IOException {
        String filename=file.getOriginalFilename();
        System.out.println("上传的文件名："+filename);
        File f=new File("D:/articleImg/"+filename);
        if (!f.getParentFile().exists()){
            f.getParentFile().mkdirs();//如果父目录不存在，创建该目录
        }
        //保存文件,将上传的文件内容写入file
        file.transferTo(f);
        Map map=new HashMap();
        map.put("src","/articleImg/"+filename);//图片访问路径
        map.put("title",filename);//图片标题
        return new MyResult<>(0,"",map);
    }

    @ResponseBody
    @PostMapping("/article/add")
    public MyResult<Map> add(Article article){
        articleService.insert(article);
        return new MyResult<>(0);
    }
}
